import {fetch} from '../../../utils/axios'
import {downExcel} from '../../../utils/common'

const state = {
  name: '部门所用资源统计报表',
  id: null,
  search: '',
  totalItems: 0,
  items: [],
  loading: true,
  pagination: {},
  headers: [],
  etext: 'No Data',
  rowsPerPageItems: [10, 50, 100, { text: 'All', value: 100000 }]
}

const mutations = {
  handlerDepartmentReport: (state) => {
    state.loading = true
    const { sortBy, descending, page, rowsPerPage } = state.pagination
    let ordering = descending ? '-' + sortBy : sortBy
    fetch('/dep_report/', {
      offset: (page - 1) * rowsPerPage,
      limit: rowsPerPage,
      ordering,
      search: state.search
    }).then((response) => {
      state.items = response.results
      state.totalItems = response.count
      state.loading = false
    }).catch((error) => {
      state.etext = error.response
    })
  },
  departmentReportDownload () {
    downExcel(state.headers, state.items)
  },
  loadDepartmentReportHeaders (state) {
    fetch('/getmodels/', {
      appname: 'report',
      modelname: 'dep_report'
    }).then((response) => {
      state.headers = JSON.parse(response)
    }).catch((error) => {
      state.etext = error.response
    })
  }
}

const actions = {
  handlerDepartmentReport: ({commit}) => {
    commit('handlerDepartmentReport')
  },
  departmentReportDownload ({commit}) {
    commit('departmentReportDownload')
  },
  loadDepartmentReportHeaders ({commit}) {
    commit('loadDepartmentReportHeaders')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
